// const fs = require('fs')
// const path = require('path')
const express = require('express')
const ctrldb = require('../utils/ctrldb')
const {creObj, creToken} = require('../utils/utils')


const router = express.Router()

// const dbPath = path.join(__dirname, '../db/login.json')
// const userData = fs.readFileSync(dbPath)
// const arrUserData = JSON.parse(userData)

// router.get('/add', (req, res, next)=>{
//     let {username, password} = req.query
//     if (username && password) {
//         arrUserData.push({id:arrUserData.length, username, password})
//         fs.writeFileSync(dbPath, JSON.stringify(arrUserData))
//         res.json({code: 1,massage: '注册成功'})
//     } else {
//         res.json({code: 0,massage: '请正确提交参数'})
//     }
// })
const argErr = creObj(0, '请正确提交参数')
const regIn = creObj(2, '当前用户已存在！')
const regSuccess = creObj(1, '注册成功')
const loginSuccess = creObj(1, '登录成功')
const loginErr = creObj(0, '登录失败')

router.get('/register', (req, res, next)=>{
    let {username, password} = req.query
    let key = username+password
    if (!username || !password) return res.json(argErr)

    ctrldb('user', (data)=>{
        let  resData = key in data ? regIn : regSuccess
        data[key] = {username, password, token:creToken()}
        res.json(resData)
        return data
    })
})


router.get('/login', (req, res, next)=>{
    let {username, password} = req.query
    let key = username+password
    ctrldb('user', (data)=>{
        let resData = key in data ? {token:data[key].token, ...loginSuccess} : loginErr
        res.json(resData)
    })
})

module.exports = router